package com.ruoyi.project.pest.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Service
public class PestDetectionService {

    private static final Logger log = LoggerFactory.getLogger(PestDetectionService.class);

    @Value("${pest.detection.api.url:http://localhost:5000}")
    private String apiUrl;

    @Value("${pest.detection.api.timeout:30000}")
    private int timeout;

    private final RestTemplate restTemplate;

    public PestDetectionService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 调用Python API进行病虫害检测
     */
    public Map<String, Object> detectPest(MultipartFile imageFile) {
        long startTime = System.currentTimeMillis();
        log.info("开始病虫害检测，文件名: {}", imageFile.getOriginalFilename());

        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 设置请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("image", imageFile.getResource());

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送请求到Python API
            String detectUrl = apiUrl + "/detect";
            log.info("调用Python API: {}", detectUrl);

            ResponseEntity<Map> response = restTemplate.exchange(
                    detectUrl,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            long endTime = System.currentTimeMillis();
            log.info("病虫害检测完成，耗时: {}ms", (endTime - startTime));

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return response.getBody();
            } else {
                log.error("检测API返回错误状态: {}", response.getStatusCode());
                throw new RuntimeException("Detection API returned error: " + response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("调用检测服务失败", e);
            throw new RuntimeException("Error calling detection service: " + e.getMessage());
        }
    }

    /**
     * 检查Python服务健康状态
     */
    public boolean isServiceHealthy() {
        try {
            String healthUrl = apiUrl + "/health";
            log.debug("检查服务健康状态: {}", healthUrl);

            ResponseEntity<Map> response = restTemplate.getForEntity(healthUrl, Map.class);
            return response.getStatusCode() == HttpStatus.OK;
        } catch (Exception e) {
            log.warn("Python服务健康检查失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 测试检测功能
     */
    public Map<String, Object> testDetection() {
        try {
            String testUrl = apiUrl + "/test";
            log.info("测试检测功能: {}", testUrl);

            ResponseEntity<Map> response = restTemplate.getForEntity(testUrl, Map.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return response.getBody();
            } else {
                throw new RuntimeException("Test API returned error: " + response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("测试检测功能失败", e);
            throw new RuntimeException("Error testing detection service: " + e.getMessage());
        }
    }
}